package com.hnxxxy.oa.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hnxxxy.oa.enums.BizCodeEnum;
import com.hnxxxy.oa.exception.BizException;
import com.hnxxxy.oa.system.mapper.SysMenuMapper;
import com.hnxxxy.oa.system.mapper.SysRoleMapper;
import com.hnxxxy.oa.system.mapper.SysRoleMenuMapper;
import com.hnxxxy.oa.system.model.SysRoleMenuDO;
import com.hnxxxy.oa.system.service.SysRoleMenuService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
* @author 周石林
* @description 针对表【sys_role_menu(角色-菜单)】的数据库操作Service实现
* @createDate 2022-05-03 15:33:13
*/
@Service
public class SysRoleMenuServiceImpl implements SysRoleMenuService{

    @Resource
    private SysRoleMenuMapper sysRoleMenuMapper;
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private SysMenuMapper sysMenuMapper;


    @Override
    public Integer grantAuthorzation(Integer[] integers) {
        int roleId=integers[0];
        if (sysRoleMapper.selectById(roleId)==null){
            throw new BizException(BizCodeEnum.ROLE_NOTEXISTS);
        }
        for(int i=1;i<integers.length;i++){
            if (sysMenuMapper.selectById(integers[i])==null){
                throw new BizException(BizCodeEnum.MENU_UNEXIST);
            }
        }
        for(int i=1;i<integers.length;i++){
            QueryWrapper<SysRoleMenuDO> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("role_id",roleId);
            queryWrapper.eq("menu_id",integers[i]);
            Integer count = sysRoleMenuMapper.selectCount(queryWrapper);
            if (count>0){
                throw new BizException(BizCodeEnum.ROLE_MENU_EXIST);
            }
        }

        for (int i=1;i<integers.length;i++){
            //构建插入数据库对象
            SysRoleMenuDO sysRoleMenuDO = new SysRoleMenuDO();
            sysRoleMenuDO.setRoleId(roleId);
            sysRoleMenuDO.setMenuId(integers[i]);
            sysRoleMenuMapper.insert(sysRoleMenuDO);
        }

        return integers.length-1;
    }

    @Override
    public boolean deleteGrantAuthorzation(Integer roleId, Integer menuId) {
        if(menuId==null && roleId==null){
            throw new BizException(BizCodeEnum.PARAM_NULL);
        }
        QueryWrapper<SysRoleMenuDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(roleId!=null,"role_id",roleId);
        queryWrapper.eq(menuId!=null,"menu_id",menuId);
        int delete = sysRoleMenuMapper.delete(queryWrapper);
        return delete==1;
    }
}